import pgzrun
import random
import pygame


# 使用精灵类型，便于碰撞判定
class GameObject(pygame.sprite.Sprite):
    # 定义构造函数
    def __init__(self, filename, location):
        # 调父类来初始化子类
        pygame.sprite.Sprite.__init__(self)
        # 加载图片
        self.image = pygame.image.load("images/"+filename)
        # 获取图片rect区域
        self.rect = self.image.get_rect()
        # 设置位置
        self.rect.topleft = location


flag = 0  # 游戏环节 0表示开始阶段，1表示第一次跳起阶段，2表示游戏阶段，3表示结束阶段
Jump = 0  # 是否跳跃 flag为2时
i = 0  # flag为1时跳跃时间
j = 0  # flag为2时跳跃时间
t = 0  # 用于出现仙人掌的时间
k = 0  # 用于计分的时间
WIDTH = 800
HEIGHT = 380
score = 0  # 积分
f = open('score', 'r')
score_max = int(f.read())  # 文件中第一次游戏时为0
f.close()

bg1 = Actor('background')
bg2 = Actor('background')
bg2.left = 800
dino = Actor('dino4')  # dino4为静止或跳起
dino.x = 50
dino.y = 310
plants = []  # 用于存储仙人掌角色
game_over = Actor('game over')
game_over.x = 400
game_over.y = 130
ret = Actor('return')
ret.x = 400
ret.y = 160

pos_dino = (50, 260)
sprite_dino = GameObject("dino4.png", pos_dino)
sprite_dino.mask = pygame.mask.from_surface(sprite_dino.image)
all_sprites = pygame.sprite.Group()
all_sprites.add(sprite_dino)


def restart():  # 重置函数
    global flag, Jump, plants, j, i, t, k, score
    Jump = 0
    flag = 2
    sprite_dino.image = 'dino1'
    sprite_dino.rect.y = 260
    bg1.left = 0
    bg2.left = 800
    plants = []
    j = 0
    i = 0
    t = 0
    k = 0
    score = 0
    all_sprites.empty()
    all_sprites.add(sprite_dino)


def draw():
    global flag
    screen.clear()
    bg1.draw()
    bg2.draw()
    score_str = str(score)
    score_max_str = str(score_max)
    all_sprites.draw(screen)
    if len(score_str) < 5:  # 分数位数小于5时用0补全
        score_str = '0' * (5 - len(score_str)) + score_str
    elif len(score_str) > 5:  # 分数位数大于5时设为99999
        score_str = '99999'
    if len(score_max_str) < 5:  # 分数位数小于5时用0补全
        score_max_str = '0' * (5 - len(score_max_str)) + score_max_str
    elif len(score_max_str) > 5:  # 分数位数大于5时设为99999
        score_max_str = '99999'
    screen.draw.text('HI   ' + score_max_str + '  ' + score_str, (600, 10), color='black')
    if flag == 3:
        game_over.draw()
        ret.draw()


def on_key_down(key):
    global flag, Jump
    if flag == 0:
        if key == keys.SPACE:
            flag = 1
    elif flag == 2:
        if key == keys.SPACE or key == keys.UP:
            Jump = 1
    elif flag == 3:
        if key == keys.SPACE:
            restart()


def on_mouse_down(pos, button):
    global flag
    if flag == 3:
        if button == mouse.LEFT and ret.collidepoint(pos):
            restart()


def update():
    global flag, i, Jump, j, t, k, score, score_max
    if flag == 1:
        if i <= 17:
            sprite_dino.rect.y -= 10
            i += 1
        elif i <= 35:
            sprite_dino.rect.y += 10
            i += 1
        else:
            i = 0
            flag = 2
            sprite_dino.image = 'dino1'
    if flag == 2:
        # 两块背景交替出现，小恐龙图片重复切换，形成小恐龙跑动的效果
        bg1.x -= 10
        bg2.x -= 10
        if bg1.right <= 0:
            bg1.left = 800
        if bg2.right <= 0:
            bg2.left = 800
        for p in plants:
            p.rect.x -= 10
            if pygame.sprite.collide_mask(p, sprite_dino):
                Jump = 0
                if sprite_dino.rect.y == 300:
                    sprite_dino.rect.y = 260
                sprite_dino.image = 'dino3'  # dino3为死亡形态
                flag = 3
                return
            if p.rect.right < 0:
                plants.remove(p)  # 仙人掌x坐标小于0时删除该仙人掌
        if Jump:
            sprite_dino.image = 'dino4'
            if j <= 17:
                sprite_dino.rect.y -= 10
                j += 1
            elif j <= 35:
                sprite_dino.rect.y += 10
                j += 1
            else:
                j = 0
                Jump = 0
                sprite_dino.image = 'dino1'
        else:
            if keyboard.down:
                if sprite_dino.image == 'dino1' or sprite_dino.image == 'dino2':
                    sprite_dino.image = 'dino5'
                if sprite_dino.image == 'dino5':  # dino5为左脚落地
                    i += 1
                    if i == 5:
                        sprite_dino.image = 'dino6'
                        i = 0
                elif sprite_dino.image == 'dino6':  # dino6为右脚落地
                    i += 1
                    if i == 5:
                        sprite_dino.image = 'dino5'
                        i = 0
                sprite_dino.rect.y = 290
            else:
                if sprite_dino.image == 'dino5' or sprite_dino.image == 'dino6':
                    sprite_dino.image = 'dino1'
                if sprite_dino.image == 'dino1':  # dino1为左脚落地
                    i += 1
                    if i == 5:
                        sprite_dino.image = 'dino2'
                        i = 0
                elif sprite_dino.image == 'dino2':  # dino2为右脚落地
                    i += 1
                    if i == 5:
                        sprite_dino.image = 'dino1'
                        i = 0
                sprite_dino.rect.y = 260
        t += 1
        if t == 90:  # update函数每秒执行60次，1.5秒产生一个新的仙人掌
            a = random.randint(1, 4)  # 1到4的随机数
            if a == 1:  # plant1大小较大，位置需偏上
                pos_plant = (800, 240)
            else:
                pos_plant = (800, 270)
            p = GameObject('plant' + str(a) + '.png', pos_plant)
            p.mask = pygame.mask.from_surface(p.image)
            all_sprites.add(p)
            plants.append(p)
            t = 0
        k += 1
        if k == 6:  # update函数每秒执行60次，每0.1秒加一分
            score += 1
            k = 0
            if score >= score_max:
                score_max = score
                fi = open('score', 'w')
                fi.write(str(score_max))
                fi.close()


pgzrun.go()
